<!-- src/views/Dashboard.vue -->
<template>
  <div>
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>图书馆管理系统</h2>
          <div>
            <!-- 主题切换按钮 -->
            <el-button type="primary" @click="toggleTheme">
              <span v-if="isDark">
                <i class="bi bi-moon-fill"></i> 深色模式
              </span>
              <span v-else>
                <i class="bi bi-sun-fill"></i> 亮色模式
              </span>
            </el-button>
            <!-- 退出按钮 -->
            <el-button type="danger" @click="handleLogout">
              <i class="bi bi-box-arrow-left"></i> 退出
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card shadow="hover">
          <el-row class="mb-3" type="flex" justify="space-between" align="middle">
            <el-col :span="24" :md="12" :lg="8">
              <!-- 移除搜索功能 -->
              <!-- 如果需要保留，可以根据后端调整 -->
            </el-col>
            <el-col :span="24" :md="12" :lg="8" class="button-group">
              <el-button type="primary" @click="showAddBookModal">
                <i class="bi bi-plus-lg"></i> 添加图书
              </el-button>
              <el-button v-if="isAdmin" type="info" @click="navigateToLogs">
                <i class="bi bi-file-earmark-text"></i> 查看日志
              </el-button>
              <el-button v-if="isAdmin" type="success" @click="navigateToUsers">
                <i class="bi bi-people-fill"></i> 用户管理
              </el-button>
              <el-button v-if="isAdmin" type="warning" @click="navigateToBorrow">
                <i class="bi bi-book-half"></i> 借阅管理
              </el-button>
            </el-col>
          </el-row>

          <!-- 加载指示器 -->
          <el-spin :loading="loading" tip="加载中...">
            <el-table v-if="books.length > 0" :data="books" style="width: 100%" stripe>
              <el-table-column prop="id" label="ID" width="50" sortable></el-table-column>
              <el-table-column prop="title" label="书名" sortable></el-table-column>
              <el-table-column prop="author" label="作者" sortable></el-table-column>
              <el-table-column prop="isbn" label="ISBN" sortable></el-table-column>
              <el-table-column prop="category" label="分类" sortable></el-table-column>
              <el-table-column prop="status" label="状态" width="100" sortable>
                <template #default="{ row }">
                  <el-tag :type="row.status === 'available' ? 'success' : 'danger'">{{ row.status === 'available' ? '可借' : '已借出' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250">
                <template #default="{ row }">
                  <div class="button-group">
                    <el-button size="mini" type="primary" @click="showEditBookModal(row)">
                      <i class="bi bi-pencil-square"></i> 编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="deleteBook(row.id)">
                      <i class="bi bi-trash-fill"></i> 删除
                    </el-button>
                    <el-button v-if="row.status === 'available'" size="mini" type="success" @click="borrowBook(row.id)">
                      <i class="bi bi-check-circle-fill"></i> 借阅
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 无数据提示 -->
            <div v-else class="no-data">
              <el-empty description="暂无数据"></el-empty>
            </div>
          </el-spin>

          <!-- 分页组件 -->
          <div class="pagination-container" v-if="total > pageSize">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              @current-change="handlePageChange"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- 添加图书对话框 -->
    <el-dialog
      title="添加图书"
      v-model="addBookVisible"
      width="50%"
      @close="closeAddBookModal"
      :teleported="false"
    >
      <el-form :model="newBook" label-width="80px">
        <el-form-item label="书名" prop="title" :rules="[{ required: true, message: '请输入书名', trigger: 'blur' }]">
          <el-input v-model="newBook.title" placeholder="请输入书名"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author" :rules="[{ required: true, message: '请输入作者', trigger: 'blur' }]">
          <el-input v-model="newBook.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="ISBN" prop="isbn" :rules="[{ required: true, message: '请输入ISBN', trigger: 'blur' }]">
          <el-input v-model="newBook.isbn" placeholder="请输入ISBN"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="newBook.category" placeholder="请输入分类"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddBookModal">取消</el-button>
        <el-button type="primary" @click="addBook">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑图书对话框 -->
    <el-dialog
      title="编辑图书"
      v-model="editBookVisible"
      width="50%"
      @close="closeEditBookModal"
      :teleported="false"
    >
      <el-form :model="editBook" label-width="80px">
        <el-form-item label="书名" prop="title" :rules="[{ required: true, message: '请输入书名', trigger: 'blur' }]">
          <el-input v-model="editBook.title" placeholder="请输入书名"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author" :rules="[{ required: true, message: '请输入作者', trigger: 'blur' }]">
          <el-input v-model="editBook.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="ISBN" prop="isbn" :rules="[{ required: true, message: '请输入ISBN', trigger: 'blur' }]">
          <el-input v-model="editBook.isbn" placeholder="请输入ISBN"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="editBook.category" placeholder="请输入分类"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editBook.status" placeholder="请选择">
            <el-option label="可借" value="available"></el-option>
            <el-option label="已借出" value="borrowed"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditBookModal">取消</el-button>
        <el-button type="primary" @click="updateBook">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'Dashboard',
  setup() {
    const router = useRouter();
    const books = ref([]);
    const addBookVisible = ref(false);
    const editBookVisible = ref(false);
    const newBook = ref({
      title: '',
      author: '',
      isbn: '',
      category: '',
    });
    const editBook = ref({});
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const loading = ref(false);
    const user = JSON.parse(localStorage.getItem('user')) || { role: 'student', username: '', id: 1 };
    const isAdmin = computed(() => user.role === 'admin');
    const isDark = ref(false);

    /**
     * 获取图书列表
     */
    const fetchBooks = () => {
      loading.value = true;
      let url = `/api/books?page=${currentPage.value}&limit=${pageSize.value}`;
      // 如果需要搜索，可以在这里添加
      // if (searchQuery.value) {
      //   url += `&search=${encodeURIComponent(searchQuery.value)}`;
      // }

      axios
        .get(url)
        .then((response) => {

          // 根据后端响应格式调整
          if (response.data.books && typeof response.data.total === 'number') {
            books.value = response.data.books;
            total.value = response.data.total;
            // 不再显示成功消息，避免分页时频繁弹出
          } else {
            ElMessage.error('获取图书列表失败，响应格式不正确');
          }

          loading.value = false;
        })
        .catch((error) => {
          console.error('获取图书列表失败:', error);
          ElMessage.error('获取图书列表失败');
          loading.value = false;
        });
    };

    /**
     * 搜索图书
     */
    // 如果不需要搜索，可以移除
    // const searchBooks = () => {
    //   currentPage.value = 1; // 重置到第一页
    //   fetchBooks();
    // };

    /**
     * 显示添加图书模态框
     */
    const showAddBookModal = () => {
      addBookVisible.value = true;
    };

    /**
     * 关闭添加图书模态框
     */
    const closeAddBookModal = () => {
      addBookVisible.value = false;
      resetNewBook();
    };

    /**
     * 添加图书
     */
    const addBook = () => {
      if (!newBook.value.title || !newBook.value.author || !newBook.value.isbn) {
        ElMessage.warning('请填写所有必填项');
        return;
      }


      axios
        .post('/api/books', { ...newBook.value, username: user.username })
        .then((response) => {

          if (response.data.success) {
            ElMessage.success(response.data.message || '添加图书成功');
            addBookVisible.value = false;
            fetchBooks();
            // 重置表单
            resetNewBook();
          } else {
            ElMessage.error(response.data.message || '添加图书失败');
          }
        })
        .catch((error) => {
          console.error('添加图书失败:', error);
          ElMessage.error('添加图书失败');
        });
    };

    /**
     * 显示编辑图书模态框
     */
    const showEditBookModal = (book) => {
      editBook.value = { ...book };
      editBookVisible.value = true;
    };

    /**
     * 关闭编辑图书模态框
     */
    const closeEditBookModal = () => {
      editBookVisible.value = false;
      resetEditBook();
    };

    /**
     * 更新图书信息
     */
    const updateBook = () => {
      if (!editBook.value.title || !editBook.value.author || !editBook.value.isbn) {
        ElMessage.warning('请填写所有必填项');
        return;
      }

      // console.log('更新图书请求数据:', editBook.value); // 调试日志

      axios
        .put(`/api/books/${editBook.value.id}`, { ...editBook.value, username: user.username })
        .then((response) => {
          // console.log('更新图书响应:', response.data); // 调试日志

          if (response.data.success) {
            ElMessage.success(response.data.message || '更新图书成功');
            editBookVisible.value = false;
            fetchBooks();
          } else {
            ElMessage.error(response.data.message || '更新图书失败');
          }
        })
        .catch((error) => {
          console.error('更新图书失败:', error);
          ElMessage.error('更新图书失败');
        });
    };

    /**
     * 删除图书
     */
    const deleteBook = (id) => {
      ElMessageBox.confirm('确定删除此图书?', '删除图书', {
        type: 'warning',
      })
        .then(() => {
          // console.log('删除图书 ID:', id); // 调试日志

          axios
            .delete(`/api/books/${id}`, { data: { username: user.username } })
            .then((response) => {
              // console.log('删除图书响应:', response.data); // 调试日志

              if (response.data.success) {
                ElMessage.success('图书删除成功');
                fetchBooks();
              } else {
                ElMessage.error(response.data.message || '删除图书失败');
              }
            })
            .catch((error) => {
              console.error('删除图书失败:', error);
              ElMessage.error('删除图书失败');
            });
        })
        .catch(() => {
          // 用户取消删除
        });
    };

    /**
     * 借阅图书
     */
    const borrowBook = (bookId) => {
      const payload = {
        user_id: user.id,
        book_id: bookId,
        username: user.username,
      };
      // console.log('借阅图书请求数据:', payload); // 调试日志

      axios
        .post('/api/borrow', payload)
        .then((response) => {
          // console.log('借阅图书响应:', response.data); // 调试日志

          if (response.data.success) {
            ElMessage.success(response.data.message || '借阅成功');
            fetchBooks();
          } else {
            ElMessage.error(response.data.message || '借阅失败');
          }
        })
        .catch((error) => {
          console.error('借阅图书失败:', error);
          ElMessage.error('借阅图书失败');
        });
    };

    /**
     * 退出登录
     */
    const handleLogout = () => {
      localStorage.removeItem('user');
      router.push('/');
      ElMessage.success('退出成功');
    };

    /**
     * 导航到日志页面
     */
    const navigateToLogs = () => {
      router.push('/logs');
    };

    /**
     * 导航到用户管理页面
     */
    const navigateToUsers = () => {
      router.push('/users');
    };

    /**
     * 导航到借阅管理页面
     */
    const navigateToBorrow = () => {
      router.push('/borrow');
    };

    /**
     * 切换主题
     */
    const toggleTheme = () => {
      isDark.value = !isDark.value;
      document.body.classList.toggle('dark-theme', isDark.value);
      // 保存用户偏好
      localStorage.setItem('theme', isDark.value ? 'dark' : 'light');
    };

    /**
     * 处理分页更改
     */
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchBooks();
    };

    /**
     * 重置添加图书表单
     */
    const resetNewBook = () => {
      newBook.value = {
        title: '',
        author: '',
        isbn: '',
        category: '',
      };
    };

    /**
     * 重置编辑图书表单
     */
    const resetEditBook = () => {
      editBook.value = {};
    };

    /**
     * 初始化时获取图书
     */
    onMounted(() => {
      // 初始化主题
      const savedTheme = localStorage.getItem('theme');
      if (savedTheme === 'dark') {
        isDark.value = true;
        document.body.classList.add('dark-theme');
      }
      fetchBooks();
    });

    return {
      books,
      addBookVisible,
      editBookVisible,
      newBook,
      editBook,
      currentPage,
      pageSize,
      total,
      loading,
      isAdmin,
      isDark,
      toggleTheme,
      handleLogout,
      showAddBookModal,
      closeAddBookModal,
      addBook,
      showEditBookModal,
      closeEditBookModal,
      updateBook,
      deleteBook,
      borrowBook,
      fetchBooks,
      handlePageChange,
      navigateToLogs,
      navigateToUsers,
      navigateToBorrow,
      resetNewBook,
      resetEditBook,
    };
  },
};
</script>

<style scoped>
/* 样式设置 */
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 提升 el-dialog 的 z-index 以确保其在顶层 */
.el-dialog__wrapper {
  z-index: 3000 !important;
}
</style>
